<template>
  <div class="content">
    <h3>二维码 识别、读取、解码</h3>
    <el-button style="width:100%" type="primary" @click="handler">选择二维码</el-button>
    <template v-if="imgurl">
      <el-divider></el-divider>
      <el-descriptions style="width:100%" :column="1" direction="vertical" :border="true">
        <el-descriptions-item label="二维码识别结果">{{ result }}</el-descriptions-item>
        <el-descriptions-item label="当前选择二维码">
          <el-image class="mmv-image" :src="imgurl"></el-image>
        </el-descriptions-item>
      </el-descriptions>
    </template>
    <template v-if="errorMessage">
      <el-divider></el-divider>
      <el-alert :title="errorMessage" type="error" :closable="false"></el-alert>
    </template>
  </div>
</template>

<script>
import jsQR from "jsqr";
import Jimp from "jimp";

export default {
  name: "Reader",
  data() {
    return {
      result: "",
      imgurl: "",
      errorMessage: "",
    };
  },
  methods: {
    async handler() {
      this.errorMessage = "";
      try {
        // 选择二维码
        const file = await this.onSelect();
        // 读取二维码文件
        const res = await this.onRead(file);
        const { data, width, height } = res.bitmap;
        // 解析二维码
        this.result = this.onAnalysis(data, width, height);
        // 设置预览图
        const createObjectURL = window.createObjectURL || window.URL.createObjectURL || window.webkitURL.createObjectUR;
        this.imgurl = createObjectURL(file);
      } catch (error) {
        console.error(error);
        this.imgurl = "";
        this.result = "";
        this.errorMessage = error.message;
      }

    },
    // 选择二维码
    onSelect() {
      return new Promise((resolve) => {
        const fileInput = document.createElement("input");
        fileInput.setAttribute("type", "file");
        fileInput.addEventListener("change", (evt) => {
          const [file] = evt.target.files;
          resolve(file);
          evt.target.value = null;
        });
        fileInput.click();
      });
    },
    // 读取二维码文件
    onRead(file) {
      return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = (evt) => {
          Jimp.read(evt.target.result).then((res) => {
            resolve(res);
          }).catch((err) => {
            console.error(err);
            reject(new Error("文件读取错误!"));
          });
        };
      });
    },
    // 解析二维码
    onAnalysis(data, width, height) {
      try {
        const res = jsQR(data, width, height);
        return res.data;
      } catch (error) {
        return "识别失败，请检查二维码是否正确！";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.mmv-image {
  width: 120px;
  height: 120px;
}
</style>